<?php
// +----------------------------------------------------------------------
// | Qbt CMS Plugin
// +----------------------------------------------------------------------
// | Copyright (c) 2012-2018 http://www.qbt8.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 黄老邪 <develop02@qbt8.com>
// +----------------------------------------------------------------------
namespace plugins\qbt_order\controller;
use think\Controller;
/**
 * 模型数据管理控制器
 */
class QbtOrderPlugin extends Controller {

    //订单列表
    public function index()
    {
        $order_list = D('Order')->order_list();
        $page_size=$order_list['filter']['page_size'];
        $record_count=$order_list['record_count'];
        $page = new \Think\Page($record_count, $page_size);
        $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        $this->assign('_page', $page->show());

        $this->assign('order_list',   $order_list['orders']);
        $this->assign('filter',       $order_list['filter']);
        $this->assign('record_count', $order_list['record_count']);
        $this->assign('page_count',   $order_list['page_count']);
        $this->assign('full_page',    1);
        $this->meta_title = '订单列表';
        $this->display('order_list');

    }
    
    
    public function order_export(){
        $excel_lsit = array();
        $order_list = D('Order')->order_list();
        if(!empty($order_list['orders'])){
            foreach ($order_list['orders'] as $key=>$value){
                $goods = D('Order')->get_order_goods($value);
                if(!empty($goods['goods_list'])){
                    foreach ($goods['goods_list'] as $k=>$v){
                        $temp = array();
                        $temp['order_sn'] = $value['order_sn'].' ';
                        $temp_user_info_arr=user_info($value['user_id']);
                        $temp['username'] = $temp_user_info_arr['user_name'].' ';
                        $temp['goods_name'] = $v['goods_name'];
                        $temp['goods_sn'] = $v['goods_sn'];
                        if($v['diy_goods_sn']){
                            $str = str_replace(array("\r\n", "\r", "\n"), "|||||", $v['goods_attr']);
                            $temp_goods_attr=explode("|||||",$str);
                            foreach($temp_goods_attr as $sub_key=>$sub_val){
            
                                if(!$sub_val){
                                    unset($temp_goods_attr[$sub_key]);
                                }else{
            
                                    $sub_goods_attr=explode("||",$sub_val);
                                    $temp_goods_attr[$sub_key]=$sub_goods_attr;
                                }
                            }
                            $v['goods_diy_attr']=$temp_goods_attr;
                            $bucket_type=M('diy_goods')->where("diy_goods_sn='".$v['diy_goods_sn']."'")->getField('bucket_type');
                            //桶的押金
                            $yajin=M('attribute_shop')->where("attr_id='242'")->find();
                            if($bucket_type==1){
                                $v['bucket_type']='18L（约15kg）';
                                $v['deposit_money']=$yajin['xdeposit'];
                            }else{
                                $v['bucket_type']='200L（约180kg）';
                                $v['deposit_money']=$yajin['ddeposit'];
                            }
                            
                            $temp['goods_attr'] = "桶规格:{$v['bucket_type']} 押金：¥{$v['deposit_money']}";
                            $temp['goods_attr'] .= PHP_EOL;
                            foreach ($temp_goods_attr as $k=>$vv){
                                $temp['goods_attr'] .= $vv[1].' ';
                                $temp['goods_attr'] .= $vv[2].'/kg ×';
                                $temp['goods_attr'] .= $vv[3];
                                $temp['goods_attr'] .= PHP_EOL;
                            }
                        }else{
                            $temp['goods_attr'] = $v['goods_attr'];
                        }
                        
                        $temp['goods_price'] = $v['goods_price'];
                        $temp['goods_number'] = $v['goods_number'];
                        $temp['formated_subtotal'] = $v['formated_subtotal'];
                        $temp['consignee'] = $value['consignee'];
                        
                        if(!empty($value['card_id'])){
                            $self_pick = M('self_pick')->where(array('id'=>$value['card_id']))->find();
                            $temp['address'] = $self_pick['province'].$self_pick['city'].$self_pick['area'].$self_pick['address'];
                        }else{
                            $temp['address'] = get_region($value['province']).get_region($value['city']).get_region($value['district']).$value['address'];
                        }
                        $temp['tel'] = $value['tel'].' ';
                        $temp['formated_order_amount'] = $value['formated_order_amount'];
                        $excel_list[] = $temp;
                    }
                }
            }
        }

        $xlsName  = "订单";
        $xlsCell  = array(
            array('order_sn','订单号',20),
            array('username','用户名',13),
            array('goods_name','商品名称',30),
            array('goods_sn','商品编码',10),
            array('goods_attr','商品属性',50),
            array('goods_price','单价',10),
            array('goods_number','数量',10),
            array('formated_subtotal','小计',10),
            array('consignee','收货人',10),
            array('address','收货地址',15),
            array('tel','电话',15),
            array('formated_order_amount','订单应付总金额',10),
        );
        $this->exportExcel($xlsName,$xlsCell,$excel_list);
    }
    
    //打印单
    public function order_print(){
        $type = I('type');
        $order_id = I('order_id');
        
        if($type == 1){
            $order = M('order_info')->where(array('order_id'=>$order_id))->find();
            $goods = D('Order')->get_order_goods($order);
            $print['order']['order_sn'] = $order['order_sn'];
            foreach ($goods['goods_list'] as $k=>$v){
                $temp = array();
                $temp['goods_name'] = $v['goods_name'];
                $temp['goods_number'] = $v['goods_number'];
                if($v['diy_goods_sn']){
                    $str = str_replace(array("\r\n", "\r", "\n"), "|||||", $v['goods_attr']);
                    $temp_goods_attr=explode("|||||",$str);
                    foreach($temp_goods_attr as $sub_key=>$sub_val){
                
                        if(!$sub_val){
                            unset($temp_goods_attr[$sub_key]);
                        }else{
                
                            $sub_goods_attr=explode("||",$sub_val);
                            $temp_goods_attr[$sub_key]=$sub_goods_attr;
                        }
                    }
                    $v['goods_diy_attr']=$temp_goods_attr;
                    $bucket_type=M('diy_goods')->where("diy_goods_sn='".$v['diy_goods_sn']."'")->getField('bucket_type');

                    //桶的押金
                    $yajin=M('attribute_shop')->where("attr_id='242'")->find();
                    if($bucket_type==1){
                        $v['bucket_type']='18L（约15kg）';
                        $v['deposit_money']=$yajin['xdeposit'];
                    }else{
                        $v['bucket_type']='200L（约180kg）';
                        $v['deposit_money']=$yajin['ddeposit'];
                    }

                
                    $temp['goods_attr'] = "桶规格:{$v['bucket_type']}";
                    $temp['goods_attr'] .= "<br/>";
                    foreach ($temp_goods_attr as $k=>$vv){
                        $temp['goods_attr'] .= $vv[1].' ';
                        $temp['goods_attr'] .= $vv[2].'/kg ×';
                        $temp['goods_attr'] .= $vv[3];
                        $temp['goods_attr'] .= "<br/>";
                    }
                }else{
                    $temp['goods_attr'] = $v['goods_attr'];
                }
                
                $print['goods_list'][] = $temp;
            }
            
        }
        
        if($type == 2){
            $order = M('order_info')->where(array('order_id'=>$order_id))->find();
            
            $print['order']['order_sn'] = $order['order_sn'];
            
            
            if(!empty($order['card_id'])){
                $self_pick = M('self_pick')->where(array('id'=>$order['card_id']))->find();
                $temp['address'] = $self_pick['province'].$self_pick['city'].$self_pick['area'].$self_pick['address'];
                
                $print['shipping']['consignee'] = $order['consignee'];
                $print['shipping']['tel'] = $order['tel'];
                $print['shipping']['address'] = $self_pick['province'].$self_pick['city'].$self_pick['area'].$self_pick['address'];
                
                
            }else{
                $print['shipping']['consignee'] = $order['consignee'];
                $print['shipping']['tel'] = $order['tel'];
                $print['shipping']['address'] = get_region($order['province']).get_region($order['city']).get_region($order['district']).$order['address'];
            }
        }
        
        if($type == 3){
            $order = M('order_info')->where(array('order_id'=>$order_id))->find();
            $goods = D('Order')->get_order_goods($order);
            $print['order']['order_sn'] = $order['order_sn'];
            $print['order']['consignee'] = $order['consignee'];
            foreach ($goods['goods_list'] as $k=>$v){
                $temp = array();
                $temp['goods_name'] = $v['goods_name'];
                $temp['goods_number'] = $v['goods_number'];
                if($v['diy_goods_sn']){
                    $str = str_replace(array("\r\n", "\r", "\n"), "|||||", $v['goods_attr']);
                    $temp_goods_attr=explode("|||||",$str);
                    foreach($temp_goods_attr as $sub_key=>$sub_val){
            
                        if(!$sub_val){
                            unset($temp_goods_attr[$sub_key]);
                        }else{
            
                            $sub_goods_attr=explode("||",$sub_val);
                            $temp_goods_attr[$sub_key]=$sub_goods_attr;
                        }
                    }
                    $v['goods_diy_attr']=$temp_goods_attr;
                    $bucket_type=M('diy_goods')->where("diy_goods_sn='".$v['diy_goods_sn']."'")->getField('bucket_type');

                    //桶的押金
                    $yajin=M('attribute_shop')->where("attr_id='242'")->find();
                    if($bucket_type==1){
                        $v['bucket_type']='18L（约15kg）';
                        $v['deposit_money']=$yajin['xdeposit'];
                    }else{
                        $v['bucket_type']='200L（约180kg）';
                        $v['deposit_money']=$yajin['ddeposit'];
                    }
            
                    $temp['goods_attr'] = "桶规格:{$v['bucket_type']}";
                    $temp['goods_attr'] .= "<br/>";
                    foreach ($temp_goods_attr as $k=>$vv){
                        $temp['goods_attr'] .= $vv[1].' ';
                        $temp['goods_attr'] .= $vv[2].'/kg ×';
                        $temp['goods_attr'] .= $vv[3];
                        $temp['goods_attr'] .= "<br/>";
                    }
                }else{
                    $temp['goods_attr'] = $v['goods_attr'];
                }
            
                $print['goods_list'][] = $temp;
            }
        }
         
        $this->assign('type',$type);
        $this->assign('print',$print);
        $this->display();
    }
    
    //支付日志
    public function order_pay_log(){
        $p = I('p','1');
        $count = M('pay_log as a')
        ->join("__ORDER_INFO__ as b on a.order_id = b.order_id")
        ->join("__USERS__ as c on b.user_id = c.user_id")
        ->field('a.*,b.order_sn,a.order_amount,c.user_name,b.add_time,b.pay_time')
        ->select();
        
        $page = new \Think\Page(count($count), 10);
        
        $list = M('pay_log as a')
        ->join("__ORDER_INFO__ as b on a.order_id = b.order_id")
        ->join("__USERS__ as c on b.user_id = c.user_id")
        ->field('a.*,b.order_sn,a.order_amount,c.user_name,b.add_time,b.pay_time')
        ->page($p,10)
        ->order("log_id desc")
        ->select();
        
        
        $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        $this->assign('_page', $page->show());
        $this->meta_title = '支付记录列表';
        $this->assign('list',$list);
        $this->display();
    }


    //订单详情
    public function info()
    {
        $order_id=I('order_id');
        $order_sn=I('order_sn');
        /* 根据订单id或订单号查询订单信息 */
        if (isset($order_id))
        {
            $order_id = intval($order_id);
            $order = order_info($order_id);
        }
        elseif (isset($order_sn))
        {
            $order_sn = trim($order_sn);
            $order = order_info(0, $order_sn);
        }
        else
        {
            /* 如果参数不存在，退出 */
            die('invalid parameter');
        }
        /* 如果订单不存在，退出 */
        if (empty($order))
        {
            die('order does not exist');
        }


        /* 取得用户名 */
        if ($order['user_id'] > 0)
        {
            $user = user_info($order['user_id']);
            if (!empty($user))
            {
                $order['user_name'] = $user['user_name'];
            }
        }
        $order['nick_name'] = $user['nick_name'];
        /* 取得区域名 */
        $sql = "SELECT concat(IFNULL(c.region_name, ''), '  ', IFNULL(p.region_name, ''), " .
            "'  ', IFNULL(t.region_name, ''), '  ', IFNULL(d.region_name, '')) AS region " .
            "FROM " .C('DB_PREFIX').'order_info'. " AS o " .
            "LEFT JOIN " . C('DB_PREFIX').'region' . " AS c ON o.country = c.region_id " .
            "LEFT JOIN " . C('DB_PREFIX').'region' . " AS p ON o.province = p.region_id " .
            "LEFT JOIN " . C('DB_PREFIX').'region' . " AS t ON o.city = t.region_id " .
            "LEFT JOIN " . C('DB_PREFIX').'region' . " AS d ON o.district = d.region_id " .
            "WHERE o.order_id = '$order[order_id]'";
        //die($sql);
        $region_list=M()->query($sql);
        $order['region'] = $region_list[0]['region'];

        /* 格式化金额 */
        if ($order['order_amount'] < 0)
        {
            $order['money_refund']          = abs($order['order_amount']);
            $order['formated_money_refund'] = price_format(abs($order['order_amount']));
        }
        $_LANG=$this->languages;
        /* 其他处理 */
        $order['order_time']    = local_date('Y-m-d H:i:s', $order['add_time']);
        $order['pay_time']      = $order['pay_time'] > 0 ?
            local_date('Y-m-d H:i:s', $order['pay_time']) : $_LANG['ps'][PS_UNPAYED];
        $order['shipping_time'] = $order['shipping_time'] > 0 ?
            local_date('Y-m-d H:i:s', $order['shipping_time']) : $_LANG['ss'][SS_UNSHIPPED];
        $order['status']        = $_LANG['os'][$order['order_status']] . ',' . $_LANG['ps'][$order['pay_status']] . ',' . $_LANG['ss'][$order['shipping_status']];
        $order['invoice_no']    = $order['shipping_status'] == SS_UNSHIPPED || $order['shipping_status'] == SS_PREPARING ? $_LANG['ss'][SS_UNSHIPPED] : $order['invoice_no'];



        /* 此订单的发货备注(此订单的最后一条操作记录) */
        $order['invoice_note'] =M('order_action')->where(" order_id = '$order[order_id]' AND shipping_status = 1  ")->order(" log_time DESC" )->getField('action_note');

        /* 取得订单商品总重量 */
        $order['total_weight'] =0.;
        /* 参数赋值：订单 */
        $this->assign('order', $order);

        /* 取得用户信息 */
        if ($order['user_id'] > 0)
        {
            /* 用户等级 */
//            if ($user['user_rank'] > 0)
//            {
//                $where = " WHERE rank_id = '$user[user_rank]' ";
//            }
//            else
//            {
//                $where = " WHERE min_points <= " . intval($user['rank_points']) . " ORDER BY min_points DESC ";
//            }
//            $user['rank_name'] = M('user_rank')->where($where)->getField('rank_name');

            // 用户红包数量
            $day    = getdate();
            $today  = local_mktime(23, 59, 59, $day['mon'], $day['mday'], $day['year']);
            $sql = "SELECT COUNT(*) as shuliang " .
                "FROM " . C('DB_PREFIX').'bonus_type'. " AS bt, " .C('DB_PREFIX').'user_bonus'. " AS ub " .
                "WHERE bt.type_id = ub.bonus_type_id " .
                "AND ub.user_id = '$order[user_id]' " .
                "AND ub.order_id = 0 " .
                "AND bt.use_start_date <= '$today' " .
                "AND bt.use_end_date >= '$today'";
            $bonus_count_list=M()->query($sql);
            $order['bonus_count'] = $bonus_count_list[0]['shuliang'];

            $this->assign('user', $user);

            // 地址信息
            $user_address_list=M('user_address')->where(" user_id = '$order[user_id]' ")->select();
            $this->assign('address_list', $user_address_list);
        }

        /* 取得订单商品及货品 */
        $goods_list = array();
        $goods_attr = array();
        $sql = "SELECT o.*, IF(o.product_id > 0, p.product_number, g.goods_number) AS storage, o.goods_attr, g.suppliers_id, IFNULL(b.brand_name, '') AS brand_name, p.product_sn
            FROM " . C('DB_PREFIX').'order_goods'. " AS o
                LEFT JOIN " .C('DB_PREFIX').'products'. " AS p
                    ON p.product_id = o.product_id
                LEFT JOIN " .C('DB_PREFIX').'goods' . " AS g
                    ON o.goods_id = g.goods_id
                LEFT JOIN " .C('DB_PREFIX').'brand' . " AS b
                    ON g.brand_id = b.brand_id
            WHERE o.order_id = '$order[order_id]'";
        $res = M()->query($sql);
       foreach($res as $row)
        {
            $row['formated_subtotal']       = price_format($row['goods_price'] * $row['goods_number']);
            $row['formated_goods_price']    = price_format($row['goods_price']);

            //edit by tiankong 20180402
            if($row['diy_goods_sn']){
                $str = str_replace(array("\r\n", "\r", "\n"), "|||||", $row['goods_attr']);
                $temp_goods_attr=explode("|||||",$str);
                foreach($temp_goods_attr as $sub_key=>$sub_val){

                    if(!$sub_val){
                        unset($temp_goods_attr[$sub_key]);
                    }else{

                        $sub_goods_attr=explode("||",$sub_val);
                        $temp_goods_attr[$sub_key]=$sub_goods_attr;
                    }
                }
                $row['goods_diy_attr']=$temp_goods_attr;
                $bucket_type=M('diy_goods')->where("diy_goods_sn='".$row['diy_goods_sn']."'")->getField('bucket_type');
                //桶的押金
                $yajin=M('attribute_shop')->where("attr_id='242'")->find();
                if($bucket_type==1){
                    $row['bucket_type']='18L（约15kg）';
                    $row['deposit_money']=$yajin['xdeposit'];
                }else{
                    $row['bucket_type']='200L（约180kg）';
                    $row['deposit_money']=$yajin['ddeposit'];
                }


            }
            //end

            $goods_attr[] = explode(' ', trim($row['goods_attr'])); //将商品属性拆分为一个数组
            $goods_list[] = $row;
        }
        $attr = array();
        foreach ($goods_attr AS $index => $array_val)
        {
            foreach ($array_val AS $value)
            {
                $arr = explode(':', $value);//以 : 号将属性拆开
                $attr[$index][] =  @array('name' => $arr[0], 'value' => $arr[1]);
            }
        }

        $this->assign('goods_attr', $attr);
        $this->assign('goods_list', $goods_list);

        /* 取得能执行的操作列表 */
        $operable_list = D('Order')->operable_list($order);
        $this->assign('operable_list', $operable_list);

        /* 取得订单操作记录 */
        $act_list = array();
        $sql = "SELECT * FROM " .C('DB_PREFIX').'order_action' . " WHERE order_id = '$order[order_id]' ORDER BY log_time DESC,action_id DESC";
        $res=M()->query($sql);
        foreach($res as $row)
        {
            $row['order_status']    = $_LANG['os'][$row['order_status']];
            $row['pay_status']      = $_LANG['ps'][$row['pay_status']];
            $row['shipping_status'] = $_LANG['ss'][$row['shipping_status']];
            $row['action_time']     = local_date("Y-m-d H:i:s", $row['log_time']);
            $act_list[] = $row;
        }
        $this->assign('action_list', $act_list);

        /* 取得是否存在实体商品 */
        $this->meta_title = '订单详情';
        $this->assign('exist_real_goods', exist_real_goods($order['order_id']));
        $this->display('order_info');


    }

    //订单操作
    public function operate(){

        $_LANG=$this->languages;
        $order_id = '';
        /* 取得订单id（可能是多个，多个sn）和操作备注（可能没有） */
        if(isset($_REQUEST['order_id']))
        {
            $order_id= $_REQUEST['order_id'];
        }
        $batch          = isset($_REQUEST['batch']); // 是否批处理
        $action_note    = isset($_REQUEST['action_note']) ? trim($_REQUEST['action_note']) : '';
        /* 确认 */
        if (isset($_POST['confirm']))
        {
            $require_note   = false;
            $action         = $_LANG['op_confirm'];
            $operation      = 'confirm';
        }
        /*------------------------------------------------------ */
        //-- start一键发货
        /*------------------------------------------------------ */
        elseif (isset($_POST['to_shipping']))
        {


            $invoice_no = empty($_REQUEST['invoice_no']) ? '' : trim($_REQUEST['invoice_no']);  //快递单号

            if (!empty($invoice_no))
            {
                $order_id = intval(trim($order_id));

                /* 查询：根据订单id查询订单信息 */
                if (!empty($order_id))
                {
                    $order = order_info($order_id);
                }
                else
                {
                    die('order does not exist');
                }

                /* 查询：取得用户名 */
                if ($order['user_id'] > 0)
                {
                    $user = user_info($order['user_id']);
                    if (!empty($user))
                    {
                        $order['user_name'] = $user['user_name'];
                    }
                }
                /* 取得订单商品 */
                $_goods = D('Order')->get_order_goods(array('order_id' => $order_id, 'order_sn' => $order['order_sn']));
                $goods_list = $_goods['goods_list'];
                foreach ($goods_list as $value)
                {

                    $sql = "UPDATE ".C('DB_PREFIX').'order_goods'. "
                SET send_number = " . $value['goods_number'] . "
                WHERE order_id = '" . $value['order_id'] . "'
                AND goods_id = '" . $value['goods_id'] . "' "."
                AND rec_id = '" . $value['rec_id'] . "' ";
                    M()->execute($sql);

                }
                /* 如果使用库存，且发货时减库存，则修改库存 */
                if ( C('STOCK_DEC_TIME') == SDT_SHIP)
                {

                    foreach ($goods_list as $value)
                    {

                        //（货品）
                        if (!empty($value['product_id']))
                        {
                            $minus_stock_sql = "UPDATE " . C('DB_PREFIX').'products' . "
                                    SET product_number = product_number - " . $value['sums'] . "
                                    WHERE product_id = " . $value['product_id'];
                            M()->execute($minus_stock_sql);
                        }

                        $minus_stock_sql = "UPDATE " . C('DB_PREFIX').'goods' . "
                                SET goods_number = goods_number - " . $value['sums'] . "
                                WHERE goods_id = " . $value['goods_id'];
                        M()->execute($minus_stock_sql);

                    }
                }

                /* 标记订单为已确认 "已发货" */
                $shipping_status =SS_SHIPPED;
                $arr['shipping_status']     = $shipping_status;
                $arr['shipping_time']       = time(); // 发货时间
                $arr['invoice_no']          = trim($order['invoice_no'] . '<br>' . $invoice_no, '<br>');
                update_order($order_id, $arr);
                /* 如果订单用户不为空，计算积分，并发给用户；发红包  发货时进行相关操作*/
                if ($order['user_id'] > 0)
                {

                    $integral = integral_to_give($order);

                    log_account_change($order['user_id'], 0, 0, intval($integral['rank_points']), intval($integral['custom_points']), sprintf('订单 %s 赠送的积分', $order['order_sn']));
                    /* 发放红包 */
                    send_order_bonus($order_id);
                }


            }

            $this->success("操作成功",U('Order/info',array("order_id"=>$order_id)));
            die();

        }
        /*------------------------------------------------------ */
       //-- end一键发货
        /*------------------------------------------------------ */
        /* 付款 */
        elseif (isset($_POST['pay']))
        {
            $require_note   = 0;
            $action         = $_LANG['op_pay'];
            $operation      = 'pay';
        }
        /* 未付款 */
        elseif (isset($_POST['unpay']))
        {

            $require_note   = 0;
            $order          = order_info($order_id);
            if ($order['money_paid'] > 0)
            {
                $show_refund = true;
            }
            $anonymous      = $order['user_id'] == 0;
            $action         = $_LANG['op_unpay'];
            $operation      = 'unpay';
        }
        /* 配货 */
        elseif (isset($_POST['prepare']))
        {
            $require_note   = false;
            $action         = $_LANG['op_prepare'];
            $operation      = 'prepare';
        }
        /* 分单 */
        elseif (isset($_POST['ship']))
        {

            $order_id = intval(trim($order_id));
            $action_note = trim($action_note);

            /* 查询：根据订单id查询订单信息 */
            if (!empty($order_id))
            {
                $order = order_info($order_id);
            }
            else
            {
                die('order does not exist');
            }

            /* 查询：根据订单是否完成 检查权限 */
            if (order_finished($order))
            {

            }
            else
            {

            }


            /* 查询：取得用户名 */
            if ($order['user_id'] > 0)
            {
                $user = user_info($order['user_id']);
                if (!empty($user))
                {
                    $order['user_name'] = $user['user_name'];
                }
            }

            /* 查询：取得区域名 */
            $sql = "SELECT concat(IFNULL(c.region_name, ''), '  ', IFNULL(p.region_name, ''), " .
                "'  ', IFNULL(t.region_name, ''), '  ', IFNULL(d.region_name, '')) AS region " .
                "FROM " . C('DB_PREFIX').'order_info' . " AS o " .
                "LEFT JOIN " . C('DB_PREFIX').'region' . " AS c ON o.country = c.region_id " .
                "LEFT JOIN " . C('DB_PREFIX').'region' . " AS p ON o.province = p.region_id " .
                "LEFT JOIN " . C('DB_PREFIX').'region' . " AS t ON o.city = t.region_id " .
                "LEFT JOIN " . C('DB_PREFIX').'region' . " AS d ON o.district = d.region_id " .
                "WHERE o.order_id = '$order[order_id]'";
            $region_list=M()->query($sql);
            $order['region'] = $region_list[0]['region'];

            /* 查询：其他处理 */
            $order['order_time']    = local_date("'Y-m-d H:i:s'", $order['add_time']);
            $order['invoice_no']    = $order['shipping_status'] == SS_UNSHIPPED || $order['shipping_status'] == SS_PREPARING ? $_LANG['ss'][SS_UNSHIPPED] : $order['invoice_no'];

            /* 查询：是否保价 */
            $order['insure_yn'] = empty($order['insure_fee']) ? 0 : 1;

            /* 查询：是否存在实体商品 */
            $exist_real_goods = exist_real_goods($order_id);

            /* 查询：取得订单商品 */
            $_goods = get_order_goods(array('order_id' => $order['order_id'], 'order_sn' =>$order['order_sn']));

            $attr = $_goods['attr'];
            $goods_list = $_goods['goods_list'];
            unset($_goods);

            /* 查询：商品已发货数量 此单可发货数量 */
            if ($goods_list)
            {
                foreach ($goods_list as $key=>$goods_value)
                {
                    if (!$goods_value['goods_id'])
                    {
                        continue;
                    }


                    $goods_list[$key]['sended'] = $goods_value['send_number'];
                    $goods_list[$key]['send'] = $goods_value['goods_number'] - $goods_value['send_number'];

                    $goods_list[$key]['readonly'] = '';
                    /* 是否缺货  发货时 */
                    if ($goods_value['storage'] <= 0  && C('STOCK_DEC_TIME') == SDT_SHIP)
                    {
                        $goods_list[$key]['send'] = $_LANG['act_good_vacancy'];
                        $goods_list[$key]['readonly'] = 'readonly="readonly"';
                    }
                    elseif ($goods_list[$key]['send'] <= 0)
                    {
                        $goods_list[$key]['send'] = $_LANG['act_good_delivery'];
                        $goods_list[$key]['readonly'] = 'readonly="readonly"';
                    }


                }
            }

            /* 模板赋值 */
            $this->assign('order', $order);
            $this->assign('exist_real_goods', $exist_real_goods);
            $this->assign('goods_attr', $attr);
            $this->assign('goods_list', $goods_list);
            $this->assign('order_id', $order_id); // 订单id
            $this->assign('operation', 'split'); // 订单id
            $this->assign('action_note', $action_note); // 发货操作信息

            /* 显示模板 */
            $this->assign('ur_here', $_LANG['order_operate'] . $_LANG['op_split']);
            $this->display('order_delivery_info');
            exit;
        }
        /* 未发货 */
        elseif (isset($_POST['unship']))
        {
            $require_note   = 0;
            $action         = $_LANG['op_unship'];
            $operation      = 'unship';
        }
        /* 收货确认 */
        elseif (isset($_POST['receive']))
        {
            $require_note   = 0;
            $action         = $_LANG['op_receive'];
            $operation      = 'receive';
        }
        /* 取消 */
        elseif (isset($_POST['cancel']))
        {
            $require_note   = 0;
            $action         = $_LANG['op_cancel'];
            $operation      = 'cancel';
            $show_cancel_note   = true;
            $order          = order_info($order_id);
            if ($order['money_paid'] > 0)
            {
                $show_refund = true;
            }
            $anonymous      = $order['user_id'] == 0;
        }
        /* 无效 */
        elseif (isset($_POST['invalid']))
        {
            $require_note   =0;
            $action         = $_LANG['op_invalid'];
            $operation      = 'invalid';
        }
        /* 退货 */
        elseif (isset($_POST['return']))
        {
            $require_note   = 0;
            $order          = order_info($order_id);
            if ($order['money_paid'] > 0)
            {
                $show_refund = true;
            }
            $anonymous      = $order['user_id'] == 0;
            $action         = $_LANG['op_return'];
            $operation      = 'return';

        }
        /* 指派 */
        elseif (isset($_POST['assign']))
        {

        }
        /* 订单删除 */
        elseif (isset($_POST['remove']))
        {
            $require_note = false;
            $operation = 'remove';
            if (!$batch)
            {
                /* 检查能否操作 */
                $order = order_info($order_id);
                $operable_list = D('Order')->operable_list($order);
                if (!isset($operable_list['remove']))
                {
                    die('Hacking attempt');
                }

                /* 删除订单 */
                M()->execute("DELETE FROM ".C('DB_PREFIX').'order_info'. " WHERE order_id = '$order_id'");
                M()->execute("DELETE FROM ".C('DB_PREFIX').'order_goods'. " WHERE order_id = '$order_id'");
                M()->execute("DELETE FROM ".C('DB_PREFIX').'order_action'. " WHERE order_id = '$order_id'");
                $action_array = array('delivery', 'back');
                D('Order')->del_delivery($order_id, $action_array);
                $this->success($_LANG['order_removed'],U('Order/index'));
                die();
            }
        }
        /* 发货单删除 */
        elseif (isset($_REQUEST['remove_invoice']))
        {
            $this->error('不允许删除发货单');
        }
        /* 退货单删除 */
        elseif (isset($_REQUEST['remove_back']))
        {
            $this->error('不允许删除订货单');
        }
        /* 批量打印订单 */
        elseif (isset($_POST['print']))
        {
            $this->error('不允许进行批量打印订单操作');
        }
        /* 去发货 */
        elseif (isset($_POST['to_delivery']))
        {
            $this->error('不允许进行去发货操作');
        }


        /* 直接处理 */
        if (!$batch)
        {
            /* 一个订单 */
            $this->redirect('Order/operate_post', array('order_id' =>$order_id,"operation"=>$operation,"action_note"=>$action_note), 0, '');
        }
        else
        {
            $this->redirect('Order/batch_operate_post', array('order_id' =>$order_id,"operation"=>$operation,"action_note"=>$action_note), 0, '');
            exit;
        }

//        /* 直接处理还是跳到详细页面 */
//        if (($require_note && $action_note == '') || isset($show_invoice_no) || isset($show_refund))
//        {
//            /* 模板赋值 */
//            $this->assign('require_note', $require_note); // 是否要求填写备注
//            $this->assign('action_note', $action_note);   // 备注
//            $this->assign('show_cancel_note', isset($show_cancel_note)); // 是否显示取消原因
//            $this->assign('show_invoice_no', isset($show_invoice_no)); // 是否显示发货单号
//            $this->assign('show_refund', isset($show_refund)); // 是否显示退款
//            $this->assign('anonymous', isset($anonymous) ? $anonymous : true); // 是否匿名
//            $this->assign('order_id', $order_id); // 订单id
//            $this->assign('batch', $batch);   // 是否批处理
//            $this->assign('operation', $operation); // 操作
//            $this->display('order_operate');
//        }
//        else
//        {
//            /* 直接处理 */
//            if (!$batch)
//            {
//                /* 一个订单 */
//                $this->redirect('Order/operate_post', array('order_id' =>$order_id,"operation"=>$operation,"action_note"=>$action_note), 0, '');
//            }
//            else
//            {
//                $this->redirect('Order/batch_operate_post', array('order_id' =>$order_id,"operation"=>$operation,"action_note"=>$action_note), 0, '');
//                exit;
//            }
//        }

    }


    public function operate_post(){

        /* 取得参数 */
        $order_id   = intval(trim($_REQUEST['order_id']));        // 订单id
        $operation  = $_REQUEST['operation'];       // 订单操作
        $_LANG=$this->languages;
        /* 查询订单信息 */
        $order = order_info($order_id);
        /* 取得备注信息 */
        $action_note = $_REQUEST['action_note'];

        /* 初始化提示信息 */
        $msg = '';
        /* 确认 */
        if ('confirm' == $operation)
        {
            /* 标记订单为已确认 */
            update_order($order_id, array('order_status' => OS_CONFIRMED, 'confirm_time' => gmtime()));
            D('Order')->update_order_amount($order_id);

            /* 如果原来状态不是“未确认”，且使用库存，且下订单时减库存，则减少库存 */
            if ($order['order_status'] != OS_UNCONFIRMED  && C('STOCK_DEC_TIME') == SDT_PLACE)
            {
                change_order_goods_storage($order_id, true, SDT_PLACE);
            }
        }
        /* 付款 */
        elseif ('pay' == $operation)
        {

            /* 标记订单为已确认、已付款，更新付款时间和已支付金额，如果是货到付款，同时修改订单为“收货确认” */
            if ($order['order_status'] != OS_CONFIRMED)
            {
                $arr['order_status']    = OS_CONFIRMED;
                $arr['confirm_time']    = gmtime();
            }
            $arr['pay_status']  = PS_PAYED;
            $arr['pay_time']    = gmtime();
            $arr['money_paid']  = $order['money_paid'] + $order['order_amount'];
            $arr['order_amount']= 0;
            $payment = payment_info($order['pay_id']);
            if ($payment['is_cod'])
            {
                $arr['shipping_status'] = SS_RECEIVED;
                $order['shipping_status'] = SS_RECEIVED;
            }
            orderpaylog($order_id, 1);

            update_order($order_id, $arr);
            /* 记录log */
            order_action($order['order_sn'], OS_CONFIRMED, $order['shipping_status'], PS_PAYED, $action_note);            

        }
        /* 设为未付款 */
        elseif ('unpay' == $operation)
        {
            /* 标记订单为未付款，更新付款时间和已付款金额 */
            $arr = array(
                'pay_status'    => PS_UNPAYED,
                'pay_time'      => 0,
                'money_paid'    => 0,
                'order_amount'  => $order['money_paid']
            );
            update_order($order_id, $arr);
            /* todo 处理退款 */
            $refund_type = @$_REQUEST['refund'];
            $refund_note = @$_REQUEST['refund_note'];

            orderpaylog($order_id, 0);

            order_refund($order, $refund_type, $refund_note);
            /* 记录log */
            order_action($order['order_sn'], OS_CONFIRMED, SS_UNSHIPPED, PS_UNPAYED, $action_note);

        }
        /* 配货 */
        elseif ('prepare' == $operation)
        {
            /* 标记订单为已确认，配货中 */
            if ($order['order_status'] != OS_CONFIRMED)
            {
                $arr['order_status']    = OS_CONFIRMED;
                $arr['confirm_time']    = gmtime();
            }
            $arr['shipping_status']     = SS_PREPARING;
            update_order($order_id, $arr);
        }
        /* 分单确认 */
        elseif ('split' == $operation)
        {

        }
        /* 设为未发货 */
        elseif ('unship' == $operation)
        {

            /* 标记订单为“未发货”，更新发货时间, 订单状态为“确认” */
            update_order($order_id, array('shipping_status' => SS_UNSHIPPED, 'shipping_time' => 0, 'invoice_no' => '', 'order_status' => OS_CONFIRMED));

            /* 如果订单用户不为空，计算积分，并退回 */
            if ($order['user_id'] > 0)
            {

                /* 计算并退回积分 */
                $integral = integral_to_give($order);
                log_account_change($order['user_id'], 0, 0, (-1) * intval($integral['rank_points']), (-1) * intval($integral['custom_points']), sprintf('由于退货或未发货操作，退回订单 %s 赠送的积分', $order['order_sn']));

                /* todo 计算并退回红包 */
                return_order_bonus($order_id);
            }

            /* 如果使用库存，则增加库存  发货时减库存*/
            if ( C('STOCK_DEC_TIME') == SDT_SHIP)
            {
                change_order_goods_storage($order['order_id'], false, SDT_SHIP);
            }

            /* 删除发货单 */
            //D('Order')->del_order_delivery($order_id);

            /* 将订单的商品发货数量更新为 0 */
            $sql = "UPDATE " .C('DB_PREFIX').'order_goods' . "
                SET send_number = 0
                WHERE order_id = '$order_id'";
            M()->execute($sql);

        }
        /* 收货确认 */
        elseif ('receive' == $operation)
        {
            /* 标记订单为“收货确认”，如果是货到付款，同时修改订单为已付款 */
            $arr = array('shipping_status' => SS_RECEIVED);
            $payment = payment_info($order['pay_id']);
            if ($payment['is_cod'])
            {
                $arr['pay_status'] = PS_PAYED;
                $order['pay_status'] = PS_PAYED;
            }
            update_order($order_id, $arr);


        }
        /* 取消 */
        elseif ('cancel' == $operation)
        {
            /* 标记订单为“取消”，记录取消原因 */
            $cancel_note = isset($_REQUEST['cancel_note']) ? trim($_REQUEST['cancel_note']) : '';
            $arr = array(
                'order_status'  => OS_CANCELED,
                'to_buyer'      => $cancel_note,
                'pay_status'    => PS_UNPAYED,
                'pay_time'      => 0,
                'money_paid'    => 0,
                'order_amount'  => $order['money_paid']
            );
            update_order($order_id, $arr);

            /* todo 处理退款 */
            if ($order['money_paid'] > 0)
            {
                $refund_type = $_REQUEST['refund'];
                $refund_note = $_REQUEST['refund_note'];
                order_refund($order, $refund_type, $refund_note);
            }

            /* 如果使用库存，且下订单时减库存，则增加库存 */
            if (C('STOCK_DEC_TIME')== SDT_PLACE)
            {
                change_order_goods_storage($order_id, false, SDT_PLACE);
            }

            /* 退还用户余额、积分、红包 */
            D('Order')->return_user_surplus_integral_bonus($order);

        }
        /* 设为无效 */
        elseif ('invalid' == $operation)
        {
            /* 标记订单为“无效”、“未付款” */
            update_order($order_id, array('order_status' => OS_INVALID));

            /* 如果使用库存，且下订单时减库存，则增加库存 */
            if ( C('STOCK_DEC_TIME') == SDT_PLACE)
            {
                change_order_goods_storage($order_id, false, SDT_PLACE);
            }

            /* 退货用户余额、积分、红包 */
            D('Order')->return_user_surplus_integral_bonus($order);
        }
        /* 退货 */
        elseif ('return' == $operation)
        {
            /* 标记订单为“退货”、“未付款”、“未发货” */
            $arr = array('order_status'     => OS_RETURNED,
                'pay_status'       => PS_UNPAYED,
                'shipping_status'  => SS_UNSHIPPED,
                'money_paid'       => 0,
                'invoice_no'       => '',
                'order_amount'     => $order['money_paid']);
            update_order($order_id, $arr);

            if ($order['pay_status'] != PS_UNPAYED)
            {
//                $refund_type = $_REQUEST['refund'];
//                $refund_note = $_REQUEST['refund'];
                $refund_type = 1;
                $refund_note = '退货';
                order_refund($order, $refund_type, $refund_note);
            }

            /* 如果订单用户不为空，计算积分，并退回 */
            if ($order['user_id'] > 0)
            {
                $goods_num = M('order_goods')->where(" order_id=".$order['order_id'])->field("goods_number, send_number")->find();;
                if($goods_num['goods_number'] == $goods_num['send_number'])
                {
                    /* 计算并退回积分 */
                    $integral = integral_to_give($order);
                    log_account_change($order['user_id'], 0, 0, (-1) * intval($integral['rank_points']), (-1) * intval($integral['custom_points']), sprintf('由于退货或未发货操作，退回订单 %s 赠送的积分', $order['order_sn']));
                }
                return_order_bonus($order_id);
            }

            if (C('STOCK_DEC_TIME') == SDT_SHIP)
            {
                change_order_goods_storage($order['order_id'], false, SDT_SHIP);
            }
            elseif (C('STOCK_DEC_TIME') == SDT_PLACE)
            {
                change_order_goods_storage($order['order_id'], false, SDT_PLACE);
            }

            /* 退货用户余额、积分、红包 */
            D('Order')->return_user_surplus_integral_bonus($order);
            M('order_goods')->where(" order_id = '$order_id' ")->setField('send_number',0);



        }
        else
        {
            die('invalid params');
        }

        $this->success('操作成功');


    }

    //批量操作订单
    public function batch_operate_post(){



        /* 取得参数 */
        $operation  = $_REQUEST['operation'];       // 订单操作
        $action_note= $_REQUEST['action_note'];     // 操作备注
        $ids =I('request.ids');
        $order_id_list = explode(',', $ids);
        $_LANG=$this->languages;
        /* 初始化处理的订单sn */
        $sn_list = array();
        $sn_not_list = array();
        /* 确认 */
        if ('confirm' == $operation)
        {
            foreach($order_id_list as $id_order)
            {
                $order=M('order_info')->where("order_sn = '$id_order' and order_status = '".OS_UNCONFIRMED."'")->find();
                if($order)
                {
                    /* 检查能否操作 */
                    $operable_list = D('Order')->operable_list($order);
                    if (!isset($operable_list[$operation]))
                    {
                        $sn_not_list[] = $id_order;
                        continue;
                    }

                    $order_id = $order['order_id'];

                    /* 标记订单为已确认 */
                    update_order($order_id, array('order_status' => OS_CONFIRMED, 'confirm_time' => gmtime()));
                    D('Order')->update_order_amount($order_id);

                    /* 记录log */
                    order_action($order['order_sn'], OS_CONFIRMED, SS_UNSHIPPED, PS_UNPAYED, $action_note);
                    $sn_list[] = $order['order_sn'];
                }
                else
                {
                    $sn_not_list[] = $id_order;
                }
            }

            $sn_str = $_LANG['confirm_order'];
        }
        /* 无效 */
        elseif ('invalid' == $operation)
        {
            foreach($order_id_list as $id_order)
            {
                $sql = "SELECT * FROM " . C('DB_PREFIX').'order_info' .
                    " WHERE order_sn = $id_order" . order_query_sql('unpay_unship');
                $temp_arr=M()->query($sql);
                $order =$temp_arr[0];
                if($order)
                {
                    /* 检查能否操作 */
                    $operable_list = D('Order')->operable_list($order);
                    if (!isset($operable_list[$operation]))
                    {
                        $sn_not_list[] = $id_order;
                        continue;
                    }

                    $order_id = $order['order_id'];

                    /* 标记订单为“无效” */
                    update_order($order_id, array('order_status' => OS_INVALID));

                    /* 记录log */
                    order_action($order['order_sn'], OS_INVALID, SS_UNSHIPPED, PS_UNPAYED, $action_note);

                    /* 如果使用库存，且下订单时减库存，则增加库存 */
                    if ( C('STOCK_DEC_TIME') == SDT_PLACE)
                    {
                        change_order_goods_storage($order_id, false, SDT_PLACE);
                    }

                    /* 退还用户余额、积分、红包 */
                    D('Order')->return_user_surplus_integral_bonus($order);

                    $sn_list[] = $order['order_sn'];
                }
                else
                {
                    $sn_not_list[] = $id_order;
                }
            }

            $sn_str = $_LANG['invalid_order'];
        }
        elseif ('cancel' == $operation)
        {
            foreach($order_id_list as $id_order)
            {
                $sql = "SELECT * FROM " . C('DB_PREFIX').'order_info' .
                    " WHERE order_sn = $id_order" . order_query_sql('unpay_unship');
                $temp_arr=M()->query($sql);
                $order =$temp_arr[0];
                if($order)
                {
                    /* 检查能否操作 */
                    $operable_list = D('Order')->operable_list($order);
                    if (!isset($operable_list[$operation]))
                    {
                        $sn_not_list[] = $id_order;
                        continue;
                    }

                    $order_id = $order['order_id'];

                    /* 标记订单为“取消”，记录取消原因 */
                    $cancel_note = trim($_REQUEST['cancel_note']);
                    update_order($order_id, array('order_status' => OS_CANCELED, 'to_buyer' => $cancel_note));

                    /* 记录log */
                    order_action($order['order_sn'], OS_CANCELED, $order['shipping_status'], PS_UNPAYED, $action_note);

                    /* 如果使用库存，且下订单时减库存，则增加库存 */
                    if (C('STOCK_DEC_TIME') == SDT_PLACE)
                    {
                        change_order_goods_storage($order_id, false, SDT_PLACE);
                    }

                    /* 退还用户余额、积分、红包 */
                    D('Order')->return_user_surplus_integral_bonus($order);

                    $sn_list[] = $order['order_sn'];
                }
                else
                {
                    $sn_not_list[] = $id_order;
                }
            }

            $sn_str = $_LANG['cancel_order'];
        }
        elseif ('remove' == $operation)
        {
            foreach ($order_id_list as $id_order)
            {
                /* 检查能否操作 */
                $order = order_info('', $id_order);
                $operable_list = D('Order')->operable_list($order);
                if (!isset($operable_list['remove']))
                {
                    $sn_not_list[] = $id_order;
                    continue;
                }

                /* 删除订单 */
                M()->execute("DELETE FROM ".C('DB_PREFIX').'order_info'. " WHERE order_id = '$order[order_id]'");
                M()->execute("DELETE FROM ".C('DB_PREFIX').'order_goods'. " WHERE order_id = '$order[order_id]'");
                M()->execute("DELETE FROM ".C('DB_PREFIX').'order_action'. " WHERE order_id = '$order[order_id]'");
                $action_array = array('delivery', 'back');
                D('Order')->del_delivery($order['order_id'], $action_array);

                $sn_list[] = $order['order_sn'];
            }

            $sn_str = $_LANG['remove_order'];
        }
        else
        {
            die('invalid params');
        }

        if(empty($sn_not_list))
        {
            $this->success('操作成功');
        }
        else
        {
            $order_list_no_fail = array();
            $sql = "SELECT * FROM " . C('DB_PREFIX').'order_info' .
                " WHERE order_sn " . db_create_in($sn_not_list);
            $res = M()->query($sql);
            foreach($res as $row)
            {
                $order_list_no_fail[$row['order_id']]['order_id'] = $row['order_id'];
                $order_list_no_fail[$row['order_id']]['order_sn'] = $row['order_sn'];
                $order_list_no_fail[$row['order_id']]['order_status'] = $row['order_status'];
                $order_list_no_fail[$row['order_id']]['shipping_status'] = $row['shipping_status'];
                $order_list_no_fail[$row['order_id']]['pay_status'] = $row['pay_status'];

                $order_list_fail = '';
                foreach(D('Order')->operable_list($row) as $key => $value)
                {
                    if($key != $operation)
                    {
                        $order_list_fail .= $_LANG['op_' . $key] . ',';
                    }
                }
                $order_list_no_fail[$row['order_id']]['operable'] = $order_list_fail;
            }
            /* 模板赋值 */

            $this->assign('order_info', $sn_str);
            $this->assign('order_list',   $order_list_no_fail);

            $this->display('order_operate_info');
        }



    }


    public function remove_order(){

        $order_sn=I('order_sn');
        if($order_sn){

            /* 检查能否操作 */
            $order = order_info('', $order_sn);
            $operable_list = D('Order')->operable_list($order);
            if (!isset($operable_list['remove']))
            {
                $sn_not_list[] = $order_sn;
                $this->error('订单不能删除');
            }
            /* 删除订单 */
            M()->execute("DELETE FROM ".C('DB_PREFIX').'order_info'. " WHERE order_id = '$order[order_id]'");
            M()->execute("DELETE FROM ".C('DB_PREFIX').'order_goods'. " WHERE order_id = '$order[order_id]'");
            M()->execute("DELETE FROM ".C('DB_PREFIX').'order_action'. " WHERE order_id = '$order[order_id]'");
            $action_array = array('delivery', 'back');
            D('Order')->del_delivery($order['order_id'], $action_array);

            $sn_list[] = $order['order_sn'];

            $this->success("删除成功");
        }else{

            $this->error("参数错误");
        }






    }

    //修改订单
    public function edit(){

        $_LANG=$this->languages;
        /* 取得参数 order_id */
        $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
        $this->assign('order_id', $order_id);
        /* 取得参数 step */
        $step_list = array('user', 'goods', 'consignee', 'shipping', 'payment', 'other', 'money');
        $step = isset($_GET['step']) && in_array($_GET['step'], $step_list) ? $_GET['step'] : 'user';
        $this->assign('step', $step);

        /* 取得参数 act */
        $act = $_GET['act'];
        $this->assign('step_act', $act);

        /* 取得订单信息 */
        if ($order_id > 0)
        {
            $order = order_info($order_id);

            /* 发货单格式化 */
            $order['invoice_no'] = str_replace('<br>', ',', $order['invoice_no']);

            /* 如果已发货，就不能修改订单了（配送方式和发货单号除外） */
            if ($order['shipping_status'] == SS_SHIPPED || $order['shipping_status'] == SS_RECEIVED)
            {
                if ($step != 'shipping')
                {
                    $this->error($_LANG['cannot_edit_order_shipped']);
                }
                else
                {
                    $step = 'invoice';
                    $this->assign('step', $step);
                }
            }

            $this->assign('order', $order);
        }
        else
        {
            if ($act != 'add' || $step != 'user')
            {
                $this->error('invalid params');
            }
        }

        /* 选择会员 */
        if ('user' == $step)
        {
            // 无操作
        }

        /* 增删改商品 */
        elseif ('goods' == $step)
        {
            /* 取得订单商品 */
            $goods_list = order_goods($order_id);
            if (!empty($goods_list))
            {
                foreach ($goods_list AS $key => $goods)
                {
                    /* 计算属性数 */
                    $attr = $goods['goods_attr'];
                    if ($attr == '')
                    {
                        $goods_list[$key]['rows'] = 1;
                    }
                    else
                    {
                        $goods_list[$key]['rows'] = count(explode(chr(13), $attr));
                    }
                }
            }

            $this->assign('goods_list', $goods_list);

            /* 取得商品总金额 */
            $this->assign('goods_amount', order_amount($order_id));
        }

        // 设置收货人
        elseif ('consignee' == $step)
        {
            /* 查询是否存在实体商品 */
            $exist_real_goods = exist_real_goods($order_id);
            $this->assign('exist_real_goods', $exist_real_goods);

            /* 取得收货地址列表 */
            if ($order['user_id'] > 0)
            {
                $this->assign('address_list', address_list($order['user_id']));

                $address_id = isset($_REQUEST['address_id']) ? intval($_REQUEST['address_id']) : 0;
                if ($address_id > 0)
                {
                    $address = address_info($address_id);
                    if ($address)
                    {
                        $order['consignee']     = $address['consignee'];
                        $order['country']       = $address['country'];
                        $order['province']      = $address['province'];
                        $order['city']          = $address['city'];
                        $order['district']      = $address['district'];
                        $order['email']         = $address['email'];
                        $order['address']       = $address['address'];
                        $order['zipcode']       = $address['zipcode'];
                        $order['tel']           = $address['tel'];
                        $order['mobile']        = $address['mobile'];
                        $order['sign_building'] = $address['sign_building'];
                        $order['best_time']     = $address['best_time'];
                        $this->assign('order', $order);
                    }
                }
            }

            if ($exist_real_goods)
            {
                /* 取得国家 */
                $this->assign('country_list', get_regions());
                if ($order['country'] > 0)
                {
                    /* 取得省份 */
                    $this->assign('province_list', get_regions(1, $order['country']));
                    if ($order['province'] > 0)
                    {
                        /* 取得城市 */
                        $this->assign('city_list', get_regions(2, $order['province']));
                        if ($order['city'] > 0)
                        {
                            /* 取得区域 */
                            $this->assign('district_list', get_regions(3, $order['city']));
                        }
                    }
                }
            }
        }

        // 选择配送方式
        elseif ('shipping' == $step)
        {
            /* 如果不存在实体商品 */
            if (!exist_real_goods($order_id))
            {
                $this->error('Hacking Attemp');
            }

            /* 取得可用的配送方式列表 */
            $region_id_list = array(
                $order['country'], $order['province'], $order['city'], $order['district']
            );
            $shipping_list = available_shipping_list($region_id_list);

            /* 取得配送费用 */
            $total = order_weight_price($order_id);
            foreach ($shipping_list AS $key => $shipping)
            {
                $shipping_fee = shipping_fee($shipping['shipping_code'],
                    unserialize($shipping['configure']), $total['weight'], $total['amount'], $total['number']);
                $shipping_list[$key]['shipping_fee'] = $shipping_fee;
                $shipping_list[$key]['format_shipping_fee'] = price_format($shipping_fee);
                $shipping_list[$key]['free_money'] = price_format($shipping['configure']['free_money']);
            }
            $this->assign('shipping_list', $shipping_list);
        }

        // 选择支付方式
        elseif ('payment' == $step)
        {
            /* 取得可用的支付方式列表 */
            if (exist_real_goods($order_id))
            {
                /* 存在实体商品 */
                $region_id_list = array(
                    $order['country'], $order['province'], $order['city'], $order['district']
                );
                $shipping_area = shipping_area_info($order['shipping_id'], $region_id_list);
                $pay_fee = ($shipping_area['support_cod'] == 1) ? $shipping_area['pay_fee'] : 0;

                $payment_list = available_payment_list($shipping_area['support_cod'], $pay_fee);
            }
            else
            {
                /* 不存在实体商品 */
                $payment_list = available_payment_list(false);
            }

            /* 过滤掉使用余额支付 */
            foreach ($payment_list as $key => $payment)
            {
                if ($payment['pay_code'] == 'balance')
                {
                    unset($payment_list[$key]);
                }
            }
            $this->assign('payment_list', $payment_list);
        }

        // 选择包装、贺卡
        elseif ('other' == $step)
        {
            /* 查询是否存在实体商品 */
            $exist_real_goods = exist_real_goods($order_id);
            $this->assign('exist_real_goods', $exist_real_goods);

            if ($exist_real_goods)
            {
                /* 取得包装列表 */
                $this->assign('pack_list', pack_list());

                /* 取得贺卡列表 */
                $this->assign('card_list', card_list());
            }
        }

        // 费用
        elseif ('money' == $step)
        {
            /* 查询是否存在实体商品 */
            $exist_real_goods = exist_real_goods($order_id);
            $this->assign('exist_real_goods', $exist_real_goods);

            /* 取得用户信息 */
            if ($order['user_id'] > 0)
            {
                $user = user_info($order['user_id']);

                /* 计算可用余额 */
                $this->assign('available_user_money', $order['surplus'] + $user['user_money']);

                /* 计算可用积分 */
                $this->assign('available_pay_points', $order['integral'] + $user['pay_points']);

                /* 取得用户可用红包 */
                $user_bonus = user_bonus($order['user_id'], $order['goods_amount']);
                if ($order['bonus_id'] > 0)
                {
                    $bonus = bonus_info($order['bonus_id']);
                    $user_bonus[] = $bonus;
                }
                $this->assign('available_bonus', $user_bonus);
            }
        }

        // 发货后修改配送方式和发货单号
        elseif ('invoice' == $step)
        {
            /* 如果不存在实体商品 */
            if (!exist_real_goods($order_id))
            {
                $this->error('Hacking Attemp');
            }

            /* 取得可用的配送方式列表 */
            $region_id_list = array(
                $order['country'], $order['province'], $order['city'], $order['district']
            );
            $shipping_list = available_shipping_list($region_id_list);
            $this->assign('shipping_list', $shipping_list);
        }

        $this->display('order_step');
    }

    //修改订单（处理提交）
    public function step_post(){

        /* 取得参数 step */
        $step_list = array('user', 'edit_goods', 'add_goods', 'goods', 'consignee', 'shipping', 'payment', 'other', 'money', 'invoice');
        $step = isset($_REQUEST['step']) && in_array($_REQUEST['step'], $step_list) ? $_REQUEST['step'] : 'user';
        $_POST=I('post.');
        /* 取得参数 order_id */
        $order_id = isset($_REQUEST['order_id']) ? intval($_REQUEST['order_id']) : 0;
        if ($order_id > 0)
        {
            $old_order = order_info($order_id);
        }
        if ('shipping' == $step)
        {
            /* 如果不存在实体商品，退出 */
            if (!exist_real_goods($order_id))
            {
                $this->error('Hacking Attemp');
            }

            /* 取得订单信息 */
            $order_info = order_info($order_id);
            $region_id_list = array($order_info['country'], $order_info['province'], $order_info['city'], $order_info['district']);

            /* 保存订单 */
            $shipping_id = $_POST['shipping'];
            $shipping = shipping_area_info($shipping_id, $region_id_list);
            $weight_amount = order_weight_price($order_id);
            $shipping_fee = shipping_fee($shipping['shipping_code'], $shipping['configure'], $weight_amount['weight'], $weight_amount['amount'], $weight_amount['number']);
            $order = array(
                'shipping_id' => $shipping_id,
                'shipping_name' => addslashes($shipping['shipping_name']),
                'shipping_fee' => $shipping_fee
            );

            if($_POST['shipping']==2 && $_POST['card_id']==''){
                $this->error('请填写自提点id');
            }elseif($_POST['shipping']==2 && $_POST['card_id']){

                $ziti_dian=M('self_pick')->where("id=".$_POST['card_id'])->count();
                if(!$ziti_dian){
                    $this->error('自提点不存在，请重新输入');
                }else{
                    $order['card_id'] = $_POST['card_id'];
                }
            }
            if (isset($_POST['insure']))
            {
                /* 计算保价费 */
                $order['insure_fee'] = shipping_insure_fee($shipping['shipping_code'], order_amount($order_id), $shipping['insure']);
            }
            else
            {
                $order['insure_fee'] = 0;
            }

            update_order($order_id, $order);
            D('Order')->update_order_amount($order_id);
            /* 更新 pay_log */
            D('Order')->update_pay_log($order_id);

            redirect(U("Order/info",array("order_id"=>$order_id)));

        }
        /* 保存发货后的配送方式和发货单号 */
        elseif ('invoice' == $step)
        {
            /* 如果不存在实体商品，退出 */
            if (!exist_real_goods($order_id))
            {
                $this->error('Hacking Attemp');
            }

            /* 保存订单 */
            $shipping_id    = $_POST['shipping'];
            $shipping       = shipping_info($shipping_id);
            $invoice_no     = trim($_POST['invoice_no']);
            $invoice_no     = str_replace(',', '<br>', $invoice_no);
            $order = array(
                'shipping_id'   => $shipping_id,
                'shipping_name' => addslashes($shipping['shipping_name']),
                'invoice_no'    => $invoice_no
            );
            update_order($order_id, $order);

            redirect(U("Order/info",array("order_id"=>$order_id)));
        }


    }
    
    private function exportExcel($expTitle,$expCellName,$expTableData){
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $fileName = $expTitle.date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
    
        vendor("PHPExcel.PHPExcel");
    
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
    
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(15);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  导出时间:'.date('Y-m-d H:i:s'));
        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]);
            if(!empty($expCellName[$i][2])){
                $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension($cellName[$i])->setWidth($expCellName[$i][2]);
            }
        }
        // Miscellaneous glyphs, UTF-8
        for($i=0;$i<$dataNum;$i++){
            for($j=0;$j<$cellNum;$j++){
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
            }
        }
    
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }


    

}